﻿@page "/music/login"

@using FreeInterface.wyymusic;
@using Models;
@using Data.DataShared;

@inject IWyyMusicHttpApi _wyyMusicHttpApi;
@inject IMessageService _message;
@inject ProtectedSessionStorage _protectedSessionStore;
@inject NavigationManager NavigationManager;

<div class="loginbox">

    <div class="messagebox">
        <Alert Type="@AlertType.Success"
               Message="本站承诺不会保存网易用户的任何信息!!!"
               ShowIcon="true"
               Closable />
    </div>
    <GridRow> 
        <GridCol Span="12">

            <div class="formbox">
                <Form Model="@phoneLogin"
                      OnFinish="LoginByPhone"
                      OnFinishFailed="OnFinishFailed"
                      ValidateMode="@FormValidateMode.Complex"
                      LabelColSpan="8"
                      WrapperColSpan="16">
                    <FormItem>
                        <Input @bind-Value="@context.Phone" />
                    </FormItem>
                    <FormItem>
                        <Input @bind-Value="@context.CheckCode" />
                    </FormItem>
                    <FormItem WrapperColOffset="8" WrapperColSpan="16">
                        <Button Type="@ButtonType.Primary" HtmlType="submit">
                            登录
                        </Button>
                        <Button Type="@ButtonType.Primary" OnClick="SentCode">
                            发送验证码
                        </Button>
                    </FormItem>
                </Form>
            </div>

        </GridCol>

        <GridCol Span="12">
            <div class="qrcodebox">
                <div>二维码扫码登录</div>
                @if (!string.IsNullOrEmpty(basecode))
                {
                    <img src="@basecode" />
                }
            </div>
        </GridCol>
    </GridRow>
</div>

@code {
    private string key;

    private string basecode;    

    private PhoneLogin phoneLogin = new PhoneLogin();

    private bool qrcodeLoginSuccess = false;

    private CountdownEvent countdownEvent = new CountdownEvent(1);

    private long? UserId = null;

    private DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));

    private Thread CheckQrcodeTheard;

    private Thread CheckStatusTheard;

    protected override async Task OnInitializedAsync()
    {
        //生成二维码
        await GenrateQrCode();
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        //状态管理
        await SetSesstionStrorage();

        CheckQrcodeTheard = new Thread(async () =>
        {
            await CheckQrCodeSuccess();
        });
        CheckStatusTheard = new Thread(async () =>
        {
            await CheckStatus();
        });

        CheckQrcodeTheard.Start();
        CheckStatusTheard.Start();
    }

    /// <summary>
    /// 获取设置sessionStorage
    /// </summary>
    /// <returns></returns>
    private async Task SetSesstionStrorage()
    {
        var result =await _protectedSessionStore.GetAsync<CurrentUserHubInfo>(WebSiteConsts.HubClientId);

        CurrentUserHubInfo? info = result.Value ?? null;

        if(info is null)
        {
            info = new CurrentUserHubInfo();

            await _protectedSessionStore.SetAsync(WebSiteConsts.HubClientId, info);
        }
    }

    private async Task GenrateQrCode()
    {
        var timestamp = (long)(DateTime.Now - startTime).TotalSeconds;

        var keymodel = await _wyyMusicHttpApi.GetWyyKey(timestamp);

        key = keymodel.Data.Unikey;

        var qrcodeTimestamp = (long)(DateTime.Now - startTime).TotalSeconds;

        var codemodel = await _wyyMusicHttpApi.GetQrCode(key,qrcodeTimestamp);

        basecode = codemodel.Data.QrImg;
    }

    private async Task LoginByPhone()
    {
        var response = await _wyyMusicHttpApi.CheckPhoneLogin(phoneLogin.Phone, phoneLogin.CheckCode);

        if (!response.Data)
        {
            await _message.Error(response.Message ?? "");
            return;
        }

        await _message.Success("二维码验证成功");
    }

    private async Task OnFinishFailed()
    {
        await _message.Error("参数校验失败");
    }

    private async Task SentCode()
    {
        if (string.IsNullOrEmpty(phoneLogin.Phone))
        {
            await _message.Warning("请先填写手机号发送验证码登录");
            return;
        }

        var sent = await _wyyMusicHttpApi.SentCode(phoneLogin.Phone);

        if (!sent.Data)
        {
            await _message.Error("验证码发送失败,我也不知道什么问题");
            return;
        }

        await _message.Success("验证码发送成功，请注意查收，10分钟内有效",3);
    }

    private async Task CheckQrCodeSuccess()
    {
        var timestamp = (long)(DateTime.Now - startTime).TotalSeconds;

        var result = await _wyyMusicHttpApi.CheckQrCode(key,timestamp);

        var polling = true;

        while (polling)
        {
            await _message.Success($"{result.Message}",1);

            await Task.Delay(300);

            timestamp = (long)(DateTime.Now - startTime).TotalSeconds;

            result = await _wyyMusicHttpApi.CheckQrCode(key,timestamp);

            if (result.Code == 803 && countdownEvent.CurrentCount > 0)
            {
                polling = false;
                countdownEvent.Signal(countdownEvent.CurrentCount);
            }
        }
    }

    private async Task CheckStatus()
    {
        //阻塞线程
        countdownEvent.Wait();

        DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));

        var timestamp = (long)(DateTime.Now - startTime).TotalSeconds;

        var result = await _wyyMusicHttpApi.CheckStatus(timestamp);

        if (result.Code == 200)
        {
            await _message.Success($"扫码成功,用户id{result.Data.Profile.UserId}", 3000);

            NavigationManager.NavigateTo("music/player");
        }
    }
}
